import { useState, useEffect } from "react";
import { Base64 } from "js-base64";
import Iconfont from "@/components/IconFont";
import BindWithSmsCode from "./Mobile";
import { loadScript, getSearchParamsObj } from "@/utils/utils.jsx";

const obj = {
	url: window.location.href?.split("?")[0],
	industrialBeltFlag: INDUSTRIAL_BELT_FLAG,
	jsoUrl: `${API_SERVER || "https://blade-gateway.test3.zhaojiafang.com"}/blade-user`
};

let vxCallbackParams = {};
export default ({ updateKey, location, wxAuthParams, handleBack, handleBindBack }) => {
	const [step, setStep] = useState(1);

	useEffect(() => {
		vxCallbackParams = {};
		if (location.search) {
			vxCallbackParams = getSearchParamsObj(location.search);
		}
		if (vxCallbackParams?.type == 2) {
			setStep(2);
		} else if (window.WxLogin) {
			step == 2 && setStep(1);
			initQrcodeFunc();
		} else {
			loadScript(`https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js`).then(() => {
				step == 2 && setStep(1);
				window.WxLogin && initQrcodeFunc();
			});
		}
	}, [updateKey]);

	const initQrcodeFunc = async () => {
		const { appId, redirectUri } = wxAuthParams;
		new WxLogin({
			appid: appId,
			self_redirect: false,
			id: "wxlogin_container",
			scope: "snsapi_login",
			redirect_uri: encodeURIComponent(redirectUri),
			state: Base64.encode(encodeURIComponent(JSON.stringify(obj))),
			href: `${window.location.hostname == "localhost" ? "http" : "https"}://${window.location.host}/static/wxQrcode.css`
		});
	};

	const bindProps = {
		type: "bind",
		handleBindBack,
		unionid: vxCallbackParams?.unionid
	};

	return (
		<>
			<span onClick={handleBack}>
				<Iconfont type="iconarrowLeft" style={{ fontSize: 28, fontWeight: "bolder", cursor: "pointer" }} />
			</span>
			{step == 1 ? (
				<>
					<div id="wxlogin_container" style={{ display: "flex", justifyContent: "center" }}></div>
				</>
			) : (
				<>
					<p className="common-color9">该微信暂未绑定，请先绑定</p>
					<BindWithSmsCode {...bindProps} />
				</>
			)}
		</>
	);
};
